package top.smallway.bs_vr;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import top.smallway.bs_vr.Okhttp.OkHttpUtils;
import top.smallway.bs_vr.check.IsExist;


public class MainActivity extends AppCompatActivity {

    private static final String AGREEMENT_PREF = "agreement_pref";
    private static final String AGREEMENT_KEY = "agreement_key";
    private PackageManager packageManager;
    private TextView loading;
    private ImageView progressBar;
    private AnimationDrawable ad;
    String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List<String> mPermissionList = new ArrayList<>();
    private static final int PERMISSION_REQUEST = 1;
    private SharedPreferences preferences;

    private final Handler mHandler = new Handler(Looper.myLooper()) {
        @Override
        public void dispatchMessage(@NonNull Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {

            super.handleMessage(msg);
            if (msg.what == 1) {
                JSONObject jsonObject = JSONObject.parseObject(String.valueOf(msg.obj));
                String version = jsonObject.getString("version");
                String downloadUrl = jsonObject.getString("download_url");
                UpdateInfo updateInfo = new UpdateInfo(version, downloadUrl);
                check(updateInfo);
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        checkPermission();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Downloadmanager();
        initview();
        initview2();
        if (!isFolderExists("/storage/emulated/0/Download/BS曲包/")){
            File folder = new File("/storage/emulated/0/Download/BS曲包/");
            folder.mkdir();
        }
        try {
            Update();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void initview2() {
        ad = (AnimationDrawable) progressBar.getDrawable();
        progressBar.postDelayed(new Runnable() {
            @Override
            public void run() {
                ad.start();
            }
        }, 100);
    }

    private void initview() {
        loading = findViewById(R.id.loading);
        progressBar=findViewById(R.id.progressBar);
        packageManager = getPackageManager();

    }

    private void showAgreementDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("协议许可").setMessage("本软件作者：碎白啊\nEmail：lizeyang@smallway.top\n1.本软件的制作目的为方便玩家使用\n2.本软件完全开源且免费，禁止用于收费、商用！").setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 将用户同意的值保存到SharedPreferences中
                        preferences = getSharedPreferences(AGREEMENT_PREF, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putBoolean(AGREEMENT_KEY, true);
                        editor.apply();
                        Intent intent = new Intent(MainActivity.this, Search_Song.class);
                        startActivity(intent);
                    }
                }).setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 如退出应用
                        finish();
                        System.exit(0);
                    }
                }).setCancelable(false) // 设置为不可取消
                .show();
    }

    private void checkPermission() {
        mPermissionList.clear();

        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         * 判断是否为空
         */
        if (mPermissionList.isEmpty()) {
            //未授予的权限为空，表示都授予了
            try {
                Update();

            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        } else {//请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST);
        }
    }
    //判断哪些权限未授予

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:
                // 用户授予了存储权限，调用checkEnable方法检查网络连接
                try {
                    Update();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }


    //    判断光团文件是否存在
    private static boolean isFolderExists(String folderPath) {
        File folder = new File(folderPath);
        return folder.exists() && folder.isDirectory();
    }

    //    判断是否有网络
    private boolean checkEnable() {
        NetworkInfo localNetworkInfo = ((ConnectivityManager) MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable())) return true;
        return false;
    }
    private boolean Downloadmanager(){
        PackageManager manager = this.getPackageManager();
        try {
            manager.getPackageInfo("com.android.providers.downloads", PackageManager.GET_ACTIVITIES);
            Log.i("OK", "Downloadmanager: ");
        } catch (PackageManager.NameNotFoundException e) {
            Log.i("NameNotFoundException", String.valueOf(e));
            throw new RuntimeException(e);
        }
        return true;
    }

    public void Update() throws IOException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                try {
                    String response = OkHttpUtils.update();
                    message.what = 1;
                    message.obj = response;
                    mHandler.sendMessage(message);
                    // 在获取更新信息后，执行检查逻辑
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

    }


    // 定义一个内部类来存储服务器返回的更新信息
    class UpdateInfo {
        private String version;
        private String downloadUrl;

        public UpdateInfo(String version, String downloadUrl) {
            this.version = version;
            this.downloadUrl = downloadUrl;
        }

        public String getVersion() {
            return version;
        }

        public String getDownloadUrl() {
            return downloadUrl;
        }
    }

    private void check(UpdateInfo updateInfo) {
        if (checkEnable()) {
            // 有网络连接
            if (!IsExist.check(packageManager)) {
                loading.setText("错误！未查找到光之乐团游戏");
            } else {
                String serverVersion = updateInfo.getVersion();
                String currentVersion = getVersion(); // 当前版本号，根据实际情况设置

                if (currentVersion.compareTo(serverVersion) < 0) {
                    // 版本低于服务器返回的版本号，通过系统浏览器访问下载链接
                    loading.setText("检测到有新版本，正在跳转下载页面");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    String downloadUrl = updateInfo.getDownloadUrl();
                    Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl));
                    startActivity(browserIntent);
                    finish();
                } else if (currentVersion.equals(serverVersion)) {
                    // 版本相等，在MainActivity跳转至Search_Song之前先调用showAgreementDialog方法
                    showAgreementDialog();
                }
            }
        } else {
            // 无网络连接
            loading.setText("无网络");
        }
    }
    public String getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "获取版本号失败";
        }
    }




}